package com.ruleengine.context.impl;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.ruleengine.context.IWorkflowConext;
import com.ruleengine.endpoint.data.IEndpointData;

/**
 * 同步对象池，用于协调请求与响应之间的同异步转换.
 * @author wuxiao
 * Created on Apr 6, 2012
 */
public class WorkflowLockPool {
    private volatile static WorkflowLockPool pool;
    private Map<String, ILockObject> lockPool;
    
    private WorkflowLockPool(){
        lockPool = new ConcurrentHashMap<String, ILockObject>();
    }
    
    public static WorkflowLockPool getInstance(){
        if(pool==null){
            synchronized(WorkflowLockPool.class){
                if(pool==null){
                    pool = new WorkflowLockPool();
                }
            }
        }
        return pool;
    }
    
    /**
     * 获取同步锁对象.
     * 同步锁对象用于同步请求和响应之间的同异步转换，
     * 以及保存异步响应结果。<p>如果同步锁对象不存在，
     * 则返回一个新建的同步锁对象。
     * @param key 工作流执行id
     * @return 同步锁对象
     */
    public ILockObject getLock(String key){
        ILockObject lk = lockPool.get(key);
        if(lk == null){
            lk = new ILockObject(){
                private IWorkflowConext context;
                private IEndpointData data;
                public IWorkflowConext getWorkflowConext() {
                    // TODO Auto-generated method stub
                    return context;
                }

                public void setWorkflowConext(IWorkflowConext context) {
                    // TODO Auto-generated method stub
                    this.context = context;
                }

                public IEndpointData getWorkflowData() {
                    // TODO Auto-generated method stub
                    return data;
                }

                public void setWorkflowData(IEndpointData data) {
                    // TODO Auto-generated method stub
                    this.data = data;
                }
            };
            lockPool.put(key, lk);
        }
        return lk;
    }
    
    /**
     * 删除同步锁对象.
     * @param key 工作流执行id
     * @return 删除的同步锁对象
     */
    public ILockObject removeLock(String key){
        return lockPool.remove(key);
    }
    
}
